import asyncio
import json
import os
import sys
from configparser import ConfigParser

import aioredis
from tornado import gen
import urllib

sys.path.append(os.path.abspath('../'))
from baseHandler import init_logger, PayHandler, Application, http_result
from channel.channel_jypay import JyPay

cfg = ConfigParser()
cfg.read('/home/pyapp/slsh/config/jypay.ini')
noti = cfg.get('log', 'noti')
logger = init_logger("jypay", noti, screen=True)
# url = cfg.get('server', 'url')
# prv = cfg.get('server', 'privkey')
# pub = cfg.get('server', 'publicKey')
# merNo = cfg.get('server', 'merNo')
# jy_pay = JyPay(url, merNo, prv, pub)

class NotiHandler(PayHandler):
    def get(self):
        logger.info(self.request.arguments)
        self.write('SUCCESS')

    @gen.coroutine
    def post(self):
        logger.info(self.request.body)


        self.write('SUCCESS')
        self.finish()
        if self.request.body.startswith(b"{"):
            data = json.loads(self.request.body.decode("utf-8"))
        else:
            data = dict(urllib.parse.parse_qsl(self.request.body.decode('utf-8')))
        if data.get("trade_no", ""):
            if data["status"] == "1":
                orderstate = "0"
            else:
                orderstate  = "1"
            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "RESP",
                "FUNCCODE": "200101",
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    'OUTERORDERNO': data["out_trade_no"],
                    'PAYORDERNO': data["trade_no"],
                    "ORDERSTATE": orderstate,
                    "OPMONEY": str(data["amount"]),
                    "REAL_FEE": str(data['fee']),
                    "PAYINFO": "SUCCESS"
                }
            }
            # 发送到核心程序
            logger.info(input_json)
            result = yield from self.pay_core("PAY_ETCPAY_PAY_RES", input_json)
            logger.info(result)
            notifyurl = result.get("NOTIFYURL", "")
            logger.info(notifyurl)

            if notifyurl:
                merchantid = result.get("MERCHANTID")
                res = yield self.merchant_exit(merchantid=merchantid)
                for i in range(5):
                    notify_data = {
                        "ordernumber": result["MERCHANTORDERNO"],
                        "respcode": result["ORDERSTATE"],
                        "merchantid": merchantid,
                        # "amount": data["amount"],
                        "businesstime": result["RESPTIME"]
                    }

                    request_obj = self.niti_data(notify_data, result)
                    rsp = yield http_result(notifyurl, request_obj, model='urlencode')
                    logger.info(rsp.body)
                    if rsp.code == 200 and rsp.body in (b'SUCCESS', b'success'):
                        logger.info("%s|%s收到下游成功应答|订单号%s", i, data["out_trade_no"], result["MERCHANTORDERNO"])
                        # noti = yield from self.pay_core("PAY_USER_REG_RES", {
                        #     "REQINFO": {"MERCHANTID": merchantid, "MERCHANTORDERNO": result["MERCHANTORDERNO"]}})
                        # logger.debug(noti)
                        break
                    else:
                        logger.info("%s|%s未收到下游成功应答|订单号%s", i, data["out_trade_no"], result["MERCHANTORDERNO"])
                        yield from asyncio.sleep(10 * (i + 1))
        else:
            # logger.info("通知|商户号%s|支付结果%s", data["merchant_no"], data["status"])
            # data = dict(urllib.parse.parse_qsl(self.request.body.decode('utf-8')))
            if data["status"] == "1":
                orderstate = "0"
            else:
                orderstate  = "1"
            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "RESP",
                "FUNCCODE": "200101",
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    "OUTERORDERNO": "",
                    "MERNO": data["merchant_no"],
                    "STATUS": orderstate,
                    "ORDERSTATE": "0",
                    "PAYINFO": "success"
                }
            }
            logger.info(input_json)
            # 发送到核心程序
            result = yield from self.pay_core("PAY_USER_REG_RES", input_json)
            logger.info(result)
            notifyurl = result.get("NOTIFYURL", "")

            if notifyurl:
                merchantid = result.get("MERCHANTID")
                res = yield self.merchant_exit(merchantid=merchantid)
                for i in range(5):
                    notify_data = {
                        "status": orderstate,
                        "sub_merchant_id": data["merchant_no"],
                        "businesstime": result["RESPTIME"]
                    }

                    request_obj = self.niti_data(notify_data, result)
                    rsp = yield http_result(notifyurl, request_obj, model='urlencode')
                    logger.info(rsp.body)
                    content = rsp.body.upper()
                    if rsp.code == 200 and rsp.body in (b'SUCCESS', b'success'):
                        logger.info("%s|%s收到下游成功应答", i, data["merchant_no"])
                        break
                    else:
                        logger.info("%s|%s未收到下游成功应答", i, data["merchant_no"])
                        yield from asyncio.sleep(10 * (i + 1))


